package cn.daenx.myadmin.modules.service.impl;

import cn.daenx.myadmin.common.constant.EventConstants;
import cn.daenx.myadmin.modules.domain.BaseEventVo;
import cn.daenx.myadmin.modules.domain.event.InjectSuccessReqVo;
import cn.daenx.myadmin.modules.service.EventHandleService;
import cn.daenx.myadmin.modules.utils.QianXunApi;
import com.alibaba.fastjson2.JSONObject;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 群成员变动事件（groupMemberChanges）
 */
@Slf4j
@Service("event:" + EventConstants.groupMemberChanges)
public class GroupMemberChangesEvent implements EventHandleService {

    @Override
    public void handle(BaseEventVo baseEventVo, JSONObject jsonObject) {
        InjectSuccessReqVo data = jsonObject.toJavaObject(InjectSuccessReqVo.class);
        BaseEventVo.Data wxdata = baseEventVo.getData();
        //用于群成员变动事件提醒
        if ("0".equals(wxdata.getEventType())) {
            //退群
            this.bye(baseEventVo,wxdata);
        }else {
            //进群
            this.welcome(baseEventVo,wxdata);
        }
    }

    @SneakyThrows
    private void welcome(BaseEventVo baseEventVo, BaseEventVo.Data wxdata) {
        JSONObject jsonObject = QianXunApi.queryObj("queryObj", wxdata.getFinalFromWxid(), "1");
        if (jsonObject != null) {
            String nick = jsonObject.getJSONObject("result").getString("nick");
            String msg = "@"+nick+" 欢迎进群";
            QianXunApi.sendText(baseEventVo.getWxid(), wxdata.getFromWxid(),msg);
        }

    }

    @SneakyThrows
    private void bye(BaseEventVo baseEventVo, BaseEventVo.Data wxdata) {
        JSONObject jsonObject = QianXunApi.queryObj("queryObj", wxdata.getFinalFromWxid(), "1");
        if (jsonObject != null) {
            String nick = jsonObject.getJSONObject("result").getString("nick");
            String msg = nick+" 已退群";
            QianXunApi.sendText(baseEventVo.getWxid(), wxdata.getFromWxid(),msg);
        }
    }
}
